<route lang="json5">
{
  style: {
    navigationBarTitleText: '情话留言'
  }
}
</route>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import { useSupabaseCoupleStore } from '@/store/supabaseCouple'
import { useToast } from 'wot-design-uni'
import dayjs from 'dayjs'
import type { Message } from '@/types/couple'

defineOptions({ name: 'Messages' })

const coupleStore = useSupabaseCoupleStore()
const { success: showSuccess } = useToast()

const newMessage = ref('')
const messageType = ref<'text' | 'voice' | 'image' | 'emoji'>('text')

// 模拟当前用户ID
const currentUserId = ref('user_001')

// Hello Kitty 风格表情包选项
const emojis = ['💕', '🎀', '🌸', '💖', '🎁', '🌺', '💝', '🦄', '🍰', '🎈', '⭐', '💫']

async function sendMessage() {
  if (!newMessage.value.trim()) return

  const message = {
    content: newMessage.value,
    type: messageType.value,
    sender: currentUserId.value,
    receiver: currentUserId.value === 'user_001' ? 'user_002' : 'user_001',
    isRead: false
  }

  await coupleStore.addMessage(message)
  newMessage.value = ''
  showSuccess('消息已发送')
}

function addEmoji(emoji: string) {
  newMessage.value += emoji
}

function chooseImage() {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      newMessage.value = res.tempFilePaths[0]
      messageType.value = 'image'
      sendMessage()
    }
  })
}

// 获取发送者名称
function getSenderName(senderId: string) {
  if (senderId === coupleStore.profile?.user1.id) return coupleStore.profile.user1.name
  if (senderId === coupleStore.profile?.user2.id) return coupleStore.profile.user2.name
  return '未知'
}

// 判断是否是自己发送的消息
function isMyMessage(senderId: string) {
  return senderId === currentUserId.value
}

const messages = computed(() => coupleStore.messages || [])

onMounted(() => {
  coupleStore.initProfile()
  
  // 初始化一些示例消息
  if (coupleStore.messages?.length === 0) {
    const sampleMessages = [
      {
        content: '今天想你了 💕',
        type: 'text' as const,
        sender: 'user_002',
        receiver: 'user_001',
        isRead: true
      },
      {
        content: '我也是，爱你 😘',
        type: 'text' as const,
        sender: 'user_001',
        receiver: 'user_002',
        isRead: true
      }
    ]
    sampleMessages.forEach(msg => coupleStore.addMessage(msg))
  }
})
</script>

<template>
  <view class="messages-container">
    <!-- 消息列表 -->
    <view class="messages-list">
      <view v-for="msg in messages" :key="msg.id" class="message-item" :class="{ 'my-message': isMyMessage(msg.sender) }">
        <view class="message-bubble">
          <view v-if="msg.type === 'text' || msg.type === 'emoji'" class="text-content">
            {{ msg.content }}
          </view>
          <image v-else-if="msg.type === 'image'" :src="msg.content" class="image-content" mode="aspectFill" 
                 @click="uni.previewImage({ current: msg.content, urls: [msg.content] })" />
          <view class="message-time">
            {{ dayjs(msg.createdAt).format('MM-DD HH:mm') }}
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view v-if="messages.length === 0" class="empty">
      <wd-icon name="chat" size="64px" color="#ccc" />
      <text class="tip">还没有消息，发送第一条情话吧～</text>
    </view>

    <!-- 输入区域 -->
    <view class="input-area">
      <!-- 表情包 -->
      <view class="emoji-panel">
        <view v-for="emoji in emojis" :key="emoji" class="emoji-item" @click="addEmoji(emoji)">
          {{ emoji }}
        </view>
      </view>
      
      <!-- 输入框 -->
      <view class="input-row">
        <wd-input 
          v-model="newMessage" 
          placeholder="说点什么..." 
          :auto-height="true"
          custom-class="message-input"
          @confirm="sendMessage"
        />
        <wd-button size="small" @click="chooseImage">
          <wd-icon name="picture" size="16px" />
        </wd-button>
        <wd-button type="primary" size="small" @click="sendMessage" :disabled="!newMessage.trim()">
          发送
        </wd-button>
      </view>
    </view>

    <wd-toast />
  </view>
</template>

<style scoped lang="scss">
.messages-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #ffb6c1 0%, #ffc0cb 50%, #ffb6c1 100%);
  display: flex;
  flex-direction: column;
  position: relative;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-image:
      radial-gradient(circle at 20% 30%, rgba(255, 182, 193, 0.3) 0%, transparent 50%),
      radial-gradient(circle at 80% 70%, rgba(255, 192, 203, 0.3) 0%, transparent 50%);
    pointer-events: none;
  }
}

.messages-list {
  flex: 1;
  padding: 16px;
  padding-bottom: 120px;
  
  .message-item {
    margin-bottom: 16px;
    display: flex;
    
    &.my-message {
      justify-content: flex-end;
      
      .message-bubble {
        background: linear-gradient(135deg, #ff69b4, #ff1493);
        color: white;
        box-shadow: 0 4px 12px rgba(255, 105, 180, 0.3);
      }
    }
    
    .message-bubble {
      max-width: 70%;
      background: white;
      border-radius: 12px;
      padding: 12px;
      box-shadow: 0 2px 8px rgba(0,0,0,0.1);
      
      .text-content {
        font-size: 14px;
        line-height: 1.5;
        word-break: break-word;
      }
      
      .image-content {
        width: 150px;
        height: 150px;
        border-radius: 8px;
      }
      
      .message-time {
        font-size: 10px;
        opacity: 0.7;
        margin-top: 6px;
        text-align: right;
      }
    }
  }
}

.empty {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #999;
  
  .tip {
    margin-top: 8px;
    font-size: 12px;
  }
}

.input-area {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  border-top: 1px solid #eee;
  padding: 12px 16px;
  padding-bottom: calc(12px + env(safe-area-inset-bottom));
  
  .emoji-panel {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-bottom: 12px;
    
    .emoji-item {
      width: 32px;
      height: 32px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #f5f5f5;
      border-radius: 6px;
      font-size: 18px;
      cursor: pointer;
      
      &:active {
        background: #e0e0e0;
      }
    }
  }
  
  .input-row {
    display: flex;
    align-items: flex-end;
    gap: 8px;
    
    .message-input {
      flex: 1;
    }
  }
}
</style>
